#ifndef LONGKEY_COMMON_PCAGENT_UTILS_H_
#define LONGKEY_COMMON_PCAGENT_UTILS_H_

#include <Windows.h>
#include <atlstr.h>

namespace pcagent_utils
{
	typedef HRESULT (*RegisterOrUnregisterFunction)(void* data, bool is_register);

	HRESULT RegisterOrUnregisterModule(bool is_machine, bool register_server,
		RegisterOrUnregisterFunction registrar, void* data);

	HRESULT RegisterOrUnregisterModuleWithTypelib(bool is_machine, bool register_server,
		RegisterOrUnregisterFunction registrar, void* data);

	CString GetCurrentVersionedName(bool is_machine,
		const TCHAR* value_name,
		const TCHAR* default_val);

	HRESULT CreateAndSetVersionedNameInRegistry(bool is_machine,
		const TCHAR* prefix,
		const TCHAR* value_name);

	// Starts an instance of the Longkey PCAgent version found in the registry.
	// Only use to start interactive processes because it uses ::ShellExecuteEx().
	// args can be NULL.
	// process can be NULL. If not NULL, caller is responsible for closing handle.
	HRESULT StartPCAgentWithArgs(bool is_machine,
		const TCHAR* args,
		HANDLE* process);

	inline int GetPacketSize(PBYTE pPacketSizeBegin, int len)
	{
		BYTE size = 8 - ((*pPacketSizeBegin & 0xE0) >> 5);
		if (size == 0 || len < size) return -1;

		int resultHigh = 0;
		PBYTE pSize = pPacketSizeBegin;

		for (int i = 1; i < size; ++i)
		{
			resultHigh <<= 8;
			resultHigh |= *(++pSize);
		}
		return resultHigh | (*pPacketSizeBegin & 0x1F);
	}
}

#endif	// LONGKEY_COMMON_PCAGENT_UTILS_H_